import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

/**
 * Upload上传组件
 * @element zss-upload
 * @slot trigger - 上传触发器
 * @slot tip - 提示文本
 */
@customElement('zss-upload')
export class ZssUpload extends LitElement {
  static styles = css`
    :host {
      display: inline-block;
    }

    .upload {
      display: inline-block;
    }

    .upload__input {
      display: none;
    }

    .upload__trigger {
      display: inline-block;
    }

    .upload__tip {
      margin-top: 8px;
      font-size: var(--zss-font-size-small);
      color: var(--zss-text-color-secondary);
    }

    .upload__file-list {
      margin-top: 8px;
    }

    .upload__file-item {
      display: flex;
      align-items: center;
      padding: 8px;
      border: 1px solid var(--zss-border-color-lighter);
      border-radius: var(--zss-border-radius-base);
      margin-bottom: 8px;
      background-color: var(--zss-fill-color-blank);
    }

    .upload__file-name {
      flex: 1;
      margin: 0 8px;
      color: var(--zss-text-color-regular);
    }

    .upload__file-status {
      margin-right: 8px;
      color: var(--zss-color-success);
    }

    .upload__file-actions {
      display: flex;
      gap: 8px;
    }

    .upload__file-action {
      cursor: pointer;
      color: var(--zss-color-primary);
      font-size: var(--zss-font-size-small);
    }

    .upload__file-action:hover {
      color: var(--zss-color-primary-light-3);
    }

    .upload__file-action--danger {
      color: var(--zss-color-danger);
    }

    .upload__file-action--danger:hover {
      color: var(--zss-color-danger-light-3);
    }

    .upload__drag {
      border: 2px dashed var(--zss-border-color);
      border-radius: var(--zss-border-radius-base);
      padding: 20px;
      text-align: center;
      background-color: var(--zss-fill-color-light);
      transition: border-color 0.2s;
    }

    .upload__drag:hover {
      border-color: var(--zss-color-primary);
    }

    .upload__drag.is-dragover {
      border-color: var(--zss-color-primary);
      background-color: var(--zss-color-primary-light-9);
    }

    .upload__drag-icon {
      font-size: 48px;
      color: var(--zss-color-info);
      margin-bottom: 16px;
    }

    .upload__drag-text {
      color: var(--zss-text-color-regular);
      margin-bottom: 8px;
    }

    .upload__drag-hint {
      color: var(--zss-text-color-secondary);
      font-size: var(--zss-font-size-small);
    }
  `;

  /**
   * 上传的URL
   * @attr action
   */
  @property({ type: String })
  action = '';

  /**
   * 上传的文件列表
   * @attr file-list
   */
  @property({ type: Array })
  fileList: Array<{ name: string; url?: string; status?: string }> = [];

  /**
   * 是否支持多选
   * @attr multiple
   */
  @property({ type: Boolean })
  multiple = false;

  /**
   * 接受上传的文件类型
   * @attr accept
   */
  @property({ type: String })
  accept = '';

  /**
   * 上传时附带的额外参数
   * @attr data
   */
  @property({ type: Object })
  data: Record<string, any> = {};

  /**
   * 设置上传的请求头部
   * @attr headers
   */
  @property({ type: Object })
  headers: Record<string, string> = {};

  /**
   * 是否支持拖拽上传
   * @attr drag
   */
  @property({ type: Boolean })
  drag = false;

  /**
   * 是否显示已上传的文件列表
   * @attr show-file-list
   */
  @property({ type: Boolean })
  showFileList = true;

  /**
   * 是否禁用
   * @attr disabled
   */
  @property({ type: Boolean })
  disabled = false;

  /**
   * 上传按钮文本
   * @attr button-text
   */
  @property({ type: String })
  buttonText = '点击上传';

  @state()
  private isDragover = false;

  private fileInput?: HTMLInputElement;

  firstUpdated() {
    this.fileInput = this.shadowRoot?.querySelector('.upload__input') as HTMLInputElement;
  }

  private handleClick() {
    if (this.disabled) return;
    this.fileInput?.click();
  }

  private handleFileChange(e: Event) {
    const input = e.target as HTMLInputElement;
    const files = input.files;
    if (files && files.length > 0) {
      this.handleFiles(files);
      input.value = '';
    }
  }

  private handleFiles(files: FileList) {
    const newFiles = Array.from(files).map(file => ({
      name: file.name,
      status: 'uploading'
    }));

    this.fileList = [...this.fileList, ...newFiles];
    
    // 模拟上传过程
    newFiles.forEach((file, index) => {
      setTimeout(() => {
        this.fileList = this.fileList.map((f, i) => 
          i === this.fileList.length - newFiles.length + index 
            ? { ...f, status: 'success' }
            : f
        );
        this.dispatchEvent(new CustomEvent('success', { 
          detail: { file: files[index], response: { url: 'https://example.com/' + file.name } }
        }));
      }, 1000);
    });

    this.dispatchEvent(new CustomEvent('change', { detail: { files: Array.from(files) } }));
  }

  private handleDragOver(e: DragEvent) {
    e.preventDefault();
    if (this.drag && !this.disabled) {
      this.isDragover = true;
    }
  }

  private handleDragLeave(e: DragEvent) {
    e.preventDefault();
    this.isDragover = false;
  }

  private handleDrop(e: DragEvent) {
    e.preventDefault();
    this.isDragover = false;
    
    if (this.drag && !this.disabled && e.dataTransfer?.files) {
      this.handleFiles(e.dataTransfer.files);
    }
  }

  private handleRemove(file: any, index: number) {
    this.fileList = this.fileList.filter((_, i) => i !== index);
    this.dispatchEvent(new CustomEvent('remove', { detail: { file } }));
  }

  private handlePreview(file: any) {
    if (file.url) {
      window.open(file.url, '_blank');
    }
    this.dispatchEvent(new CustomEvent('preview', { detail: { file } }));
  }

  render() {
    return html`
      <div class="upload">
        <input
          class="upload__input"
          type="file"
          ?multiple=${this.multiple}
          accept=${this.accept}
          @change=${this.handleFileChange}
        />
        
        ${this.drag ? html`
          <div
            class="upload__drag ${this.isDragover ? 'is-dragover' : ''}"
            @click=${this.handleClick}
            @dragover=${this.handleDragOver}
            @dragleave=${this.handleDragLeave}
            @drop=${this.handleDrop}
          >
            <div class="upload__drag-icon">📁</div>
            <div class="upload__drag-text">将文件拖到此处，或${this.buttonText}</div>
            <div class="upload__drag-hint">支持单个或批量上传</div>
          </div>
        ` : html`
          <div class="upload__trigger" @click=${this.handleClick}>
            <slot name="trigger">
              <zss-button ?disabled=${this.disabled}>
                ${this.buttonText}
              </zss-button>
            </slot>
          </div>
        `}
        
        <div class="upload__tip">
          <slot name="tip"></slot>
        </div>
        
        ${this.showFileList && this.fileList.length > 0 ? html`
          <div class="upload__file-list">
            ${this.fileList.map((file, index) => html`
              <div class="upload__file-item">
                <span class="upload__file-status">
                  ${file.status === 'success' ? '✅' : file.status === 'uploading' ? '⏳' : '❌'}
                </span>
                <span class="upload__file-name">${file.name}</span>
                <div class="upload__file-actions">
                  ${file.url ? html`
                    <span class="upload__file-action" @click=${() => this.handlePreview(file)}>
                      预览
                    </span>
                  ` : ''}
                  <span 
                    class="upload__file-action upload__file-action--danger" 
                    @click=${() => this.handleRemove(file, index)}
                  >
                    删除
                  </span>
                </div>
              </div>
            `)}
          </div>
        ` : ''}
      </div>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'zss-upload': ZssUpload;
  }
}